<?php
header("Content-Type: text/html; charset=utf-8");

$code = $_GET['code'];//获取code

$vod_id = $_GET['vod_id'];

$web_url="http://yourweb.com/vod";//网址

$appId = "wx*************"; /*appId*/  
$appsecret = "*************"; /*appsecret*/  





$weixin2 =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code");

$jsondecode2 = json_decode($weixin2); //对JSON格式的字符串进行编码
$array2 = get_object_vars($jsondecode2);//转换成数组
$a_token = $array2['access_token'];
$openid = $array2['openid'];

$weixin3 =  file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$a_token&openid=$openid");
$jsondecode3 = json_decode($weixin3); //对JSON格式的字符串进行编码
$array3 = get_object_vars($jsondecode3);//转换成数组
$user_name=$array3["nickname"];
$user_head=$array3["headimgurl"];
$sex=$array3["sex"];
$country=$array3["country"];
$province=$array3["province"];
$city=$array3["city"];
$language=$array3["language"];

if ($openid==""){
	echo "<script language='javascript'>".chr(13);
    echo "window.document.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5700ff467cd45a67&redirect_uri=".$web_url."/index.php?vod_id=".$vod_id."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'".chr(13);
    echo "</script>".chr(13);
	exit();
	}


$timestamp = time();
$jsapi_ticket = make_ticket($appId,$appsecret);
$nonceStr = make_nonceStr();
if ($_SERVER['QUERY_STRING']!=""){
   $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
}else{
	$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
	}
$signature = make_signature($nonceStr,$timestamp,$jsapi_ticket,$url);


function make_nonceStr()
{
	$codeSet = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	for ($i = 0; $i<16; $i++) {
		$codes[$i] = $codeSet[mt_rand(0, strlen($codeSet)-1)];
	}
	$nonceStr = implode($codes);
	return $nonceStr;
}

function make_signature($nonceStr,$timestamp,$jsapi_ticket,$url)
{
	$tmpArr = array(
	'noncestr' => $nonceStr,
	'timestamp' => $timestamp,
	'jsapi_ticket' => $jsapi_ticket,
	'url' => $url
	);
	ksort($tmpArr, SORT_STRING);
	$string1 = http_build_query( $tmpArr );
	$string1 = urldecode( $string1 );
	$signature = sha1( $string1 );
	return $signature;
}

function make_ticket($appId,$appsecret)
{
	// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
	$data = json_decode(file_get_contents("access_token.json"));
	if ($data->expire_time < time()) {
		$TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appsecret;
		$json = file_get_contents($TOKEN_URL);
		$result = json_decode($json,true);
		$access_token = $result['access_token'];
		if ($access_token) {
			$data->expire_time = time() + 7000;
			$data->access_token = $access_token;
			$fp = fopen("access_token.json", "w");
			fwrite($fp, json_encode($data));
			fclose($fp);
		}
	}else{
		$access_token = $data->access_token;
	}

	// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
	$data = json_decode(file_get_contents("jsapi_ticket.json"));
	if ($data->expire_time < time()) {
		$ticket_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
		$json = file_get_contents($ticket_URL);
		$result = json_decode($json,true);
		$ticket = $result['ticket'];
		if ($ticket) {
			$data->expire_time = time() + 7000;
			$data->jsapi_ticket = $ticket;
			$fp = fopen("jsapi_ticket.json", "w");
			fwrite($fp, json_encode($data));
			fclose($fp);
		}
	}else{
		$ticket = $data->jsapi_ticket;
	}

	return $ticket;
}




include 'db.php';/*连接数据库*/


//读取参数
$result = mysql_query("SELECT * FROM vod_project where id=".$vod_id);
	while($row = mysql_fetch_array($result))
	{
		$vod_title=$row['title'];       //标题
		$vod_banner=$row['banner'];	    //头图
		$vod_other=$row['other'];       //其他文字
		$vod_number=$row['number']+1;   //访问量
		$vod_class=$row['vod_class'];   //播放类型 1为直播，2为点播
		$channel_id=$row['channel_id']; //播放ID
		}
		mysql_query("UPDATE vod_project SET number=".$vod_number." WHERE id =".$vod_id); 

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<title>
<?=$vod_title?>
</title>
<style type="text/css">
body {
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
}
.chat_bg .user_chat_bg {
	width: 80%;
	margin-right: 10%;
	margin-left: 10%;
	margin-top: 10px;
	overflow: auto;
}
.chat_bg .user_chat_bg .user_head {
	width: 10%;
	float: left;
}
.chat_bg .user_chat_bg .user_head img {
	width: 100%;
}
.chat_bg .user_chat_bg .user_right {
	width: 88%;
	float: left;
	margin-left: 2%;
}
.chat_bg .user_chat_bg .user_right .user_name {
	font-family: "微软雅黑";
	font-size: 15px;
	line-height: 30px;
	height: 30px;
}
.chat_bg .user_chat_bg .user_right .user_talk {
	font-family: "微软雅黑";
	font-size: 13px;
	line-height: 30px;
	text-indent: 1em;
	background-color: #EEEEEE;
	margin-top: 5px;
	margin-bottom: 5px;
}
.chat_input {
	width: 100%;
	height: 42px;
	overflow: auto;
	background-color: #242424;
}
.chat_input input {
	height: 42px;
	width: 65%;
	float: left;
	border: none;
	color: #FFF;
	background-color: #242424;
}
.chat_input .button {
	height: 42px;
	width: 20%;
	float: right;
	background-color: #b8b8b8;
	font-family: "微软雅黑";
	font-size: 13px;
	line-height: 42px;
	text-align: center;
}
.vod_bg {
	position: relative;
}
.vod_bg .danmu_bg {
	position: absolute;
	top: 0px;
	right: 0px;
	z-index: 999;
	pointer-events: none;
	overflow: hidden;
}
.string {
	font-size: 13px;
	line-height: 25px;
	color: #FFF;
	padding-top: 3px;
	padding-right: 5px;
	padding-bottom: 3px;
	padding-left: 5px;
	background-color: #000;
	position: absolute;
	pointer-events: none;
 border-radius: 12.5px  height:25px;
	overflow: hidden;
	cursor: pointer;
	white-space: nowrap;
}
.vod_bg #danmu_bg .string img {
	margin: 2px;
	float: left;
	height: 21px;
	width: 21px;
	border-radius: 10.5px
}
.open-danmaku {
	height: 42px;
	width: 42px;
	background: url(http://img1.gtimg.com/news/pics/hv1/183/119/2088/135802728.png) no-repeat center;
	-webkit-background-size: 25px;
	background-size: 25px;
	left: 0;
	bottom: -42px;
	z-index: 10;
	float: left;
}
.lipin {
	font-family: "微软雅黑";
	font-size: 15px;
	line-height: 50px;
	height: 50px;
	background-color: #F90;
	text-align: center;
	color: #FFF;
	margin-top: 5px;
}
.tongji {
	position: absolute;
	left: 10px;
	top: 10px;
	color: #FFF;
	font-size: 12px;
	padding: 0 20px;
	background: url(http://img1.gtimg.com/news/pics/hv1/6/89/2060/133974201.png) no-repeat 4px center;
	-webkit-background-size: 12px 12px;
	background-size: 12px 12px;
}
</style>
</head>
<body>
<img src="<?=$vod_banner?>" width="100%" /> 
<!--视频播放 S-->
<div class="vod_bg" id="vod_bg">
	<div id="mod_player"><!-- 这个div是播放器准备输出的位置 --></div>
	<div class="danmu_bg" id="danmu_bg"> </div>
	<DIV class='tongji' id='tongji'><span id='user_tongji'>
		<?=$vod_number;?>
		</span></DIV>
</div>
<script src="http://imgcache.qq.com/tencentvideo_v1/tvp/js/tvp.player_v2.js" type="text/javascript" ></script> 
<script language="javascript">
		
	var win_width=$(window).width();
	var win_height=$(window).height();
	
	var vod_height=640/(1135/win_width);
	
	//设置弹幕尺寸 S
		document.getElementById('danmu_bg').style.width=win_width + 'px';
		document.getElementById('danmu_bg').style.height=vod_height + 'px';
	//设置弹幕尺寸 E
			var video = new tvp.VideoInfo();
			<?php
				if ($vod_class==1){
					echo "video.setChannelId(\"".$channel_id."\");";
					}else{
						echo "video.setVid(\"".$channel_id."\");";
						}
			?>
			//video.setChannelId("l03133vdk1r");  //直播ID
			//video.setVid("l03133vdk1r");          //点播ID
			var player = new tvp.Player();
			player.create({
				width: win_width,
				height: vod_height,
				type: <?=$vod_class?>, //1为直播，2为点播
				video: video,
				modId: "mod_player",
				autoplay: true
			});
</script> 
<!--视频播放 E-->

<div class="chat_input">
	<div class="open-danmaku" id="open-danmuku"></div>
	<input name="user_talk" type="text" id="user_talk" placeholder="请输入消息" value="" maxlength="35">
	<div class="button" id="chat_send">发送</div>
</div>
<script>
  $("#user_talk").width((win_width-42)-(win_width/100)*30)
  var danmuku=0;
  $('#open-danmuku').click(function() {
	  if (danmuku==0){
		  danmuku=1;
		  $("#open-danmuku").css({'background':'url("img/dm_hide.png") no-repeat center','background-size':'25px','-webkit-background-size':'25px','width':'42px','height':'42px'});

		  $("#danmu_bg").hide();
		  }else{
			  danmuku=0;
		 	  $("#open-danmuku").css({'background':'url("img/dm.png") no-repeat center','background-size':'25px','-webkit-background-size':'25px','width':'42px','height':'42px'});

			  $("#danmu_bg").show();
			  }
  });
</script>
<div class="chat_bg" id="chat_bg">
	<?php
$new_chat=0;
$result = mysql_query("SELECT * FROM vod_chat where vod_id=".$vod_id." order by id desc");
	while($row = mysql_fetch_array($result))
	{   
	$new_chat=$new_chat+1;
	$new_danmu[$new_chat]['user_head']=$row['user_head'];
	$new_danmu[$new_chat]['user_talk']=$row['user_talk'];
?>
	<div class="user_chat_bg">
		<div class="user_head"> <img src="<?=$row['user_head']?>" /> </div>
		<div class="user_right">
			<div class="user_name">
				<?=$row['user_name']?>
			</div>
			<div class="user_talk">
				<?=$row['user_talk']?>
			</div>
		</div>
	</div>
	<?php } 
$result = mysql_query("SELECT * FROM vod_chat where vod_id=".$vod_id);
while($row = mysql_fetch_array($result))
	{ 
	  $chat_id=$row['id'];
	 }
?>
</div>
<script>
getcontent();//初始获取数据

//提交聊天信息
var send_chat_number=0;
$("#chat_send").click(function(){
	
	

	if (send_chat_number==0){
		
		
		
	    var user_talk = document.getElementById("user_talk").value; 
		
		if (user_talk.length>0){
		
		document.getElementById("user_talk").value="";
	    send_chat_number=1;
		
		
		$("#chat_bg").html("<div class='user_chat_bg'><div class='user_head'><img src='<?=$user_head?>' /></div><div class='user_right'><div class='user_name'><?=$user_name?></div><div class='user_talk'>"+ user_talk +"</div></div></div>" +$("#chat_bg").html());
		
		danmu_auto(user_talk,"<?=$user_head?>"); //发送弹幕
		
		
		
		$.ajax({
          type: "GET",
          url: "<?=$web_url?>/chat_add.php?openid=<?=$openid?>&vod_id=<?=$vod_id?>&user_name=<?=$user_name?>&user_head=<?=$user_head?>&user_talk=" + user_talk +"&callback=?",
          dataType: "jsonp",
          jsonp: 'callback',
          success: function(json) {
			//getcontent();//获取数据
            return true;
          }
        });
		
		}
		
		
	}else{
		alert("发送消息太频繁了！");
		}
		
});






//获取最新数据，每10秒刷新一次
      var chat_id=<?=$chat_id?>;

      var int = self.setInterval(function() {
		  
	   if (send_chat_number>0){
		   send_chat_number=send_chat_number-1;
		   }
        
        	getcontent();//获取数据
      },
      10000)
      
	  

//获取数据函数 
function getcontent(){ 
$.ajax({
          type: "GET",
          url: "<?=$web_url?>/chat_json.php?vod_id=<?=$vod_id?>&chat_id="+ chat_id +"&callback=?",
          dataType: "jsonp",
          jsonp: 'callback',
          success: function(json) {
			 

			$("#user_tongji").text(json.user_number);
				
			
			 
			json = eval(json);

			for (var i=1;i<=getJsonLength(json.chat_content[0]);i++){	
			    if (chat_id<json['chat_content'][0]['chat'+i][0]['user_cid']){
					
					if (json['chat_content'][0]['chat'+i][0]['openid']!="<?=$openid?>"){ //忽略自己发出的消息
						$("#chat_bg").html("<div class='user_chat_bg'><div class='user_head'><img src='"+ json['chat_content'][0]['chat'+i][0]['user_head'] +"' /></div><div class='user_right'><div class='user_name'>"+ json['chat_content'][0]['chat'+i][0]['user_name'] +"</div><div class='user_talk'>"+ json['chat_content'][0]['chat'+i][0]['user_talk'] +"</div></div></div>" +$("#chat_bg").html());
						danmu_auto(json['chat_content'][0]['chat'+i][0]['user_talk'],json['chat_content'][0]['chat'+i][0]['user_head']);
						chat_id=json['chat_content'][0]['chat'+i][0]['user_cid'];
					}
				
				}
		      }
	
			
            return true;
          }
        });
}
		

function getJsonLength(jsonData){ 
	var jsonLength = 0; 
	for(var item in jsonData){ 
	jsonLength++; 
} 
	return jsonLength;
 } //获取JSON长度  
	  

//新进入页面弹幕
var new_danmu =new Array();
<?php
for ($i=1;$i<=$new_chat;$i++){
	echo "new_danmu[".$i."]=new Array();\r\n";
	echo "new_danmu[".$i."][1]='".$new_danmu[$i]['user_head']."';\r\n";
	echo "new_danmu[".$i."][2]='".$new_danmu[$i]['user_talk']."';\r\n";
}
?>


var danmu_xunhuan=1;
var danmu_xunhuan2=5;
var danmu_xunhuan_end=<?=$new_chat?>;
var danmu_int = self.setInterval(function() {
		
		for (var danmu_i=danmu_xunhuan;danmu_i<=danmu_xunhuan2;danmu_i++){	
		    if (danmu_i>=danmu_xunhuan_end){
				clearInterval(danmu_int);
				return false;
				}
			danmu_auto(new_danmu[danmu_i][2],new_danmu[danmu_i][1]);
			if (danmu_i==danmu_xunhuan2){
				danmu_xunhuan=danmu_xunhuan2;
				danmu_xunhuan2=danmu_xunhuan2+5;
				return false;
				}
			}  
	   
      },
      3000)


  
	  
//弹幕
var danmu_list=0;
var danmu_speed=10000;
function danmu_auto(user_chat_text,user_chat_head){
	  if (user_chat_head!=""){
            var creSpan=$("<div class='string'></div>");
            var text='<img src="'+user_chat_head+'"/>'+user_chat_text;
		    
			creSpan.html(text);
			
			Top=25*danmu_list+5;
			danmu_speed=parseInt(2000*(Math.random()))+8000;
			
            creSpan.css({"top":Top,"left":win_width+300,"borderRadius":25});
            $("#danmu_bg").append(creSpan);
            var spanDom=$("#danmu_bg>div:last-child");
            spanDom.stop().animate({"left":-300},danmu_speed,"linear",function(){
                        $(this).remove();
                    });
					
			danmu_list=danmu_list+1;
			if (danmu_list==5){danmu_list=0;}
			
			
        }
	}
</script>
</body>
</html>
